<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户列表</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <link rel="stylesheet" href="./css/user-manage.css">
    <style>
        .container{
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 查询条件区域 -->
        <div class="panel panel-default">
              <div class="panel-heading">
                    <h3 class="panel-title">用户查询</h3>
              </div>
              <div class="panel-body">
                    <div class="row">
                        <!-- 查询条件输入框 -->
                        <div class="col-xs-3 col-sm-3 col-md-3 col-lg-3">
                            <input type="text" id="userName" class="form-control" placeholder="请输入用户姓名">
                        </div>
                        <div class="col-xs-3 col-sm-3 col-md-3 col-lg-3">
                            <!-- 查询按钮 -->
                            <button type="button" onclick="getUserList()" class="btn btn-primary">查询</button>
                            <!-- 增加按钮 -->
                            <button type="button" onclick="addUser()" class="btn btn-primary">增加</button>
                            <button type="button" onclick="loopData()" class="btn btn-primary">查看</button>
                        </div>
                    </div>
              </div>
        </div>
        
        <!-- 用户新增 -->
        <div id="addUserNode" class="panel panel-default">
            <div class="panel-heading">
                  <h3 class="panel-title">用户新增</h3>
            </div>
            <div class="panel-body">
                  <div class="row userNodeBox" id="userNodeBox">
                    
                  </div>
                  <button type="submit" onclick="addUserEvt()" class="btn btn-primary">提交</button>
                  <button type="input" onclick="cancelAddUserEvt()" class="btn btn-primary">取消</button>
            </div>
      </div>

        <!-- 查询结果 -->
        <div class="panel panel-default">
              <div class="panel-heading">
                    <h3 class="panel-title">查询结果列表</h3>
              </div>
              <div class="panel-body">
                    <table class="table table-striped table-hover">
                        <!-- 表头 -->
                        <thead>
                            <tr>
                                <th>用户名</th>
                                <th>用户性别</th>
                                <th>用户手机号</th>
                                <th>用户邮箱</th>
                                <th>用户部门</th>
                                <th>用户职位</th>
                                <th>备注</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <!-- 表体 -->
                        <tbody id="userListNode">
                            <!-- 内容区域 -->
                            
                        </tbody>
                    </table>
              </div>
        </div>
    </div>
    <!-- template模板库 -->
    <script src="https://cdn.bootcdn.net/ajax/libs/art-template/4.13.2/lib/template-web.min.js"></script>
    <!-- 用户列表数据模板渲染 -->
    <script type="text/html" id="userListTpl">
        {{each userList user}}
        <tr>
            <td>{{user.userName}}</td>
            <td>{{user.userSex}}</td>
            <td>{{user.userTele}}</td>
            <td>{{user.userEmail}}</td>
            <td>{{user.userDept}}</td>
            <td>{{user.userPosition}}</td>
            <td>{{user.userRemark}}</td>
            <td>
                <button type="submit" onclick=modifyUser({{user}})
                    class="btn btn-xs btn-warning">修改</button>
                <button type="submit" onclick=deleteUser({{user}})
                    class="btn btn-xs btn-danger">删除</button>
            </td>
        </tr>
        {{/each}}
    </script>
    <!-- 新增用户数据 -->
    <script type="text/html" id="addUserTpl">
        <div class="pic">
            <span></span><img src="" id="photoImgNode" alt="" title="头像">
        </div>
        {{each userObj user}}
            {{if user.isBtn}}
            <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">
                <div class="form-group">
                    <label for="">{{user.name}}</label>
                    <div class="input-group">
                        <div onclick="addPhoto()" class="input-group-addon">图片</div>
                        <input type={{user.type}} class="form-control" id={{user.key}} value={{user.value}}>
                    </div>    
                </div>
            </div>
            {{else}}
                <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">
                    <div class="form-group">
                        <label for="">{{user.name}}</label>
                        <input type={{user.type}} class="form-control" id={{user.key}} value={{user.value}}>
                    </div>
                </div>
            {{/if}}
        {{/each}}
    </script>
    <script src="https://cdn.bootcdn.net/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
    <script>
        $('#addUserNode').hide()
        var userObj = [
                {name: '用户编码', value: '', key: 'userId', type: 'text'},
                {name: '用户名称', value: '', key: 'userName', type: 'text'},
                {name: '用户密码', value: '', key: 'userPwd', type: 'text'},
                {name: '用户性别', value: '', key: 'userSex', type: 'text'},
                {name: '出生日期', value: '', key: 'userDate', type: 'Date'},
                {name: '用户地址', value: '', key: 'userAddress', type: 'text'},
                {name: '用户头像', value: '', key: 'userPhoto', type: 'text' , isBtn:true},
                {name: '用户手机', value: '', key: 'userTele', type: 'text'},
                {name: '用户邮箱', value: '', key: 'userEmail', type: 'text'},
                {name: '入职日期', value: '', key: 'userEntry', type: 'Date'},
                {name: '用户部门', value: '', key: 'userDept', type: 'text'},
                {name: '用户职位', value: '', key: 'userPosition', type: 'text'},
                {name: '用户权限', value: '', key: 'userRole', type: 'text'},
                {name: '用户备注', value: '', key: 'userRemark', type: 'text'},
                {name: '用户状态', value: '', key: 'state', type: 'text'}
            ],
            isModify = false;
        
            $(() =>{
            /** 初始化查询---查询所有信息来渲染页面 */
            getUserList()
        }) 
        /** 用户查询信息 */   
        function getUserList () {
            var userName = $('#userName').val()
            $.ajax({
                url : `/user/list?userName=${userName}`,
                method : 'get',
                success : function (data) {
                    if(data.code === 200 && !!data.body){
                        $('#userListNode').html(template('userListTpl',{userList:data.body}))
                    }else{
                        alert('查询用户信息失败')
                    }
                },
                error : function (e) {
                    alert('网络错误，请重试')
                    console.log(e)
                }
            })
        }
        /** 用户新增页面 */
        function addUser () {
            isModify = false;
            $('#addUserNode').show()
            $('#userNodeBox').html(template('addUserTpl',{userObj}))
        }
        /** 用户新增页面提交 */
        function addUserEvt () {
            var userInput = $('#userNodeBox').find('input'),
                params = {}
            userInput.each((i,item) => {
                params[$(item).attr('id')] = $(item).val()
            })
            var SessionUser = JSON.parse(sessionStorage.getItem('user_info'))
            if(!!SessionUser){
                if(!isModify){
                    params = CryptoJS.AES.encrypt(JSON.stringify(params),SessionUser.token).toString()
                }
            }
            console.log(params)
            $.ajax({
                url : isModify ?　`/user/${params.userId}` : '/user/add',
                method : isModify ? 'put' : 'post',
                data : isModify ? params : {str:params},
                headers : {token : SessionUser.token},
                success : function(data) {
                    if(data.code === 200 && !!data.body){
                        alert(data.message)
                        getUserList()
                        $('#addUserNode').hide()
                    }else{
                        alert(data.message)
                    }
                },
                error : function(e) {
                    alert('网络错误，请重试')
                    console.log(e)
                }
            })
        }
        /** 取消新增用户 */
        function cancelAddUserEvt () {
            $('#addUserNode').hide()
        }
        /** 修改用户数据 */
        function modifyUser (user) {
            isModify = true;
            console.log(user)
            $('#addUserNode').show()
            var _user = JSON.parse(JSON.stringify(userObj))
            console.log(_user)
            _userObj = _user.map((_user,index) => {
                if(_user.key === 'userDate' || _user.key === 'userEntry'){
                    if(!!user[_user.key]){
                        _user.value = user[_user.key].substring(0,10)
                    }
                } else {
                    _user.value = user[_user.key]
                }
                return _user
            })
            $('#userNodeBox').html(template('addUserTpl',{userObj : _userObj}))
        }
        /** 删除用户数据 */
        function deleteUser (user) {
                if(confirm('确定要删除吗?')){
                    user.state = 0
                $.ajax({
                    url : `user/${user.userId}`,
                    method : 'DELETE',
                    data : user,
                    success : function (data) {
                        if(data.code === 200) {
                            alert('删除用户数据成功')
                            getUserList()
                        }else{
                            alert(data.message)
                        }
                    },
                    error : function (e) {
                        alert('网络错误，请重试')
                    }
                })
            }
        }

        function addPhoto() {
            var input = $('<input>')
            input.css('height',0).css('width',0).css('overflow','hidden').attr('type','file').appendTo($('body'))
            input.on('change',(e) => {
                var files = e.target.files;
                console.log(files)
                var formData = new FormData();
                for (var i = 0;i < files.length;i ++) {
                    formData.append('fileName', files[i]);
                }
                console.log(formData)
                $.ajax({
                    url : '/file/upload',
                    method : 'post',
                    data : formData,
                    cache : false,  /** 解决304报错 */
                    contentType :false,
                    processData : false,
                    success : function (data) {
                        if(data.code === 200) {
                            $('#photoImgNode').attr('src',data.body);
                        }
                    },
                    error : function (e) {
                        alert('网络错误，请重试')
                        console.log(e)
                    }
                })
                input.remove()
            })
            input.click()
        }

        /** 跳转代办页面 */
        function loopData() {
            window.open('./loop-data.html','_self')
        }
    </script>
</body>
</html>